﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 同步CRM物流发运单信息_晶硅
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoCRMFyInfoJGController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMStoCRMFyInfoJGController(ILogger<TMStoCRMFyInfoJGRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            //_logger = loggerFactory.CreateLogger<TMStoCRMFyInfoJGController>();
        }

        /// <summary>
        /// 同步CRM物流发运单信息_晶硅
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSAddFyInfoJG([FromBody] TMStoCRMFyInfoJGRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMStoCRMWayBillInfoResponseDto re = new TMStoCRMWayBillInfoResponseDto();
            CRM_CreateFyInfoRequestDto strRequest = new CRM_CreateFyInfoRequestDto();
            string waybill_no = strparm.waybill_no;
            string ddm_token_crm = "&token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY2NDg0NTIwNzk2MTciLCJ4ZGFwdXNlcmlkIjoiMTAwMzQwMTY3MDY0NjI5MDE4NjI0IiwieGRhcHRpbWVzdGFtcCI6IjA0MDhiZDhlY2VmZGM4NDg0MDkxOTBkOTM0NWUzMDBlOTFlZDQ3ZGQ1Y2ZhNTA0ODZhN2IzZWJmZjIzMTJhZjIzOWFlMjA5ZWJiZGI3OTNjZWYzZDE3ZWE1Y2RmYzJkMDAzNzhiYjUwYzM3NjdlMzE1NDI5YmIxNmNlMTgxYjUyYTZlYWM4MzE0Nzg3MDZlNTNkM2Q3NGY1OTlkZDVkNjdhYTdkNjY0MzQ1YjRhOWQwNTFmNzU3MTk3MjFlYWUwNjY3MGFlYzM1YzQ5NTczYTdmNDJhN2JiNTgwNTcifQ==&download=download&formId=67107c3d72a36d3165c8d3c5&uuid=0854437598cabccfe16c551e";
            int ydzt = 0;//运单状态
            int zt = 0;

            try
            {

                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }           
                if (strMsg == "")
                {
                
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                    urldic.Add("function_description", "内部:晶硅CRM同步物流状态");//查看URL配置表地址描述
                    DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                    if (url_dt.Rows.Count > 0)
                    {
                        dic.Add("waybill_no", waybill_no);
                        //DataTable wl_dt = MethodHelp.GetTableInfo("TMS0094", dic, con);//晶硅物流信息获取
                        DataTable wl_dt = MethodHelp.GetTableInfo("TMS0097", dic, con);//晶硅物流信息获取
                        if (wl_dt.Rows.Count > 0)
                        {
                            List<CRM_CreateFyInfo_mainTable> data_input = new List<CRM_CreateFyInfo_mainTable>();//operationinfo赋值

                            foreach (DataRow item in wl_dt.Rows)
                            {                               
                                int sfyqs = 1;//是否签收
                                int shipping_status = 1;//运输状态
                                string qszt = "";
                                if (item["receipt_adjunct"].ToString() == "")
                                {
                                    sfyqs = 1;
                                    ydzt = 2;
                                    shipping_status = 1;
                                    qszt = "未签收";
                                }
                                else
                                {
                                    sfyqs = 0;
                                    ydzt = 4;
                                    shipping_status = 3;
                                    qszt = "已签收";
                                }

                             
                                List<CRM_CreateFyInfo_qsdfj> qsdfj_input = new List<CRM_CreateFyInfo_qsdfj>();


                                if (item["receipt_adjunct"].ToString() != "")
                                {
                                    var fj = JsonConvert.DeserializeObject<DDM__adjunct[]>(item["receipt_adjunct"].ToString());
                                    if (fj != null)
                                    {
                                        foreach (var rows in fj)
                                        {
                                            //mainTable_input赋值
                                            qsdfj_input.Add(new CRM_CreateFyInfo_qsdfj
                                            {
                                                name = rows.fileName,
                                                content = rows.url+ ddm_token_crm,
                                                fileId= rows.id
                                            });
                                        }
                                    }
                                }
                                else
                                {   //mainTable_input赋值
                                    qsdfj_input.Add(new CRM_CreateFyInfo_qsdfj
                                    {
                                        name = "无",
                                        content = "",
                                        fileId=""
                                    });

                                }

                                data_input.Add(new CRM_CreateFyInfo_mainTable
                                {
                                qsdfj = qsdfj_input,
                                xsddh = item["saleorder_no"].ToString(),
                                ddxh = item["saleorderline_no"].ToString(),
                                qssl = DB.ToDecimal(item["qty"].ToString()),
                                wlfy = 0,
                                yszt = DB.ToInt(shipping_status),
                                sfyqs = sfyqs,
                                qsrq = DB.ToDateTime(item["receipt_date"].ToString()).ToString("yyyy-MM-dd"),
                                khbm = item["waybill_no"].ToString(),
                                cph = item["car_no"].ToString(),
                                wlbm = item["material_code"].ToString(),
                                wlmc = item["material_name"].ToString(),
                                wldw = "",
                                ddsl = DB.ToDecimal(0),
                                pdatjsl = DB.ToDecimal(item["qty"].ToString()),
                                fhdz = "",
                                shdz = item["delivery_address"].ToString(),
                                shr = "",
                                shdh = "",
                                xshth = "",
                                qsdh = item["receipt_no"].ToString(),
                                qszt = qszt,
                                sj = item["driver_name"].ToString(),
                                khmc = item["customer_name"].ToString(),
                                chrq = DB.ToDateTime(item["shipping_date"].ToString()).ToString("yyyy-MM-dd"),
                                hth = "",
                                ddlx = "",
                                fhsl = DB.ToDecimal(item["qty"].ToString()),
                                ydzt = ydzt,
                                khbh = item["customer_code"].ToString(),
                                xsddid = item["saleorder_no"].ToString(),
                                xsddxid = item["saleorderline_id"].ToString(),
                                ckdh = item["delivery_no"].ToString(),
                                songhdh = item["delivery_no"].ToString(),
                                yjft = 0,
                                fyjhls = "",
                                zt = zt,
                                ydzbid = item["waybill_no"].ToString(),
                                xsddmxid = item["autoid"].ToString(),
                                szjd = item["factory_code"].ToString(),
                                wlqsdid = "",
                                dddxh="",
                                dwxsddh = item["end_saleorderno"].ToString(),
                                dwxsddxid= item["end_saleorderlineno"].ToString()
                                });                                                               
                            }

                            if (data_input != null)
                            {
                                strRequest.mainTable = data_input;
                            }

                            string jsonText = JsonConvert.SerializeObject(strRequest);
                            var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                            //var reAgv = DB.httpPost("http://172.16.6.190:81/gokinsolar/esb/oa/api/tms/updateLogistics36", jsonText, "", "否");
                            CRM_CreateFyInfoResponseDto psp = JsonConvert.DeserializeObject<CRM_CreateFyInfoResponseDto>(reAgv);
                            if (psp.oa.code != "1")
                            {
                                strMsg = strMsg + "-" + "CRM ERR:" + psp.oa.msg;
                            }
                        }
                        else
                        {
                            strMsg = "单号=<" + waybill_no + "> 找不到对应明细记录!";
                        }
                    }                 
                    
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            //_logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
